<template>
  <el-card
    class="datastore-conterner"
    :body-style="{ height: 'calc(100% - 100px)' }"
  >
    <template #header>
      <div class="datastore-query" :style="{ height: '90px' }">
        <div class="datastore-query-title">
          <span class="normal-title">数据存储</span><span class="title-description">管理所有数据存储</span>
        </div>
        <el-form
          class="datastore-query-form"
          :model="datastoreQueryFormData"
          :inline="true"
        >
          <el-form-item label="工作空间 :">
            <el-select
              v-model="datastoreQueryFormData.workspace"
              filterable
              clearable
              placeholder="请选择工作空间"
            >
              <el-option
                v-for="workspaceItem in workspaceList"
                :key="workspaceItem.name"
                :label="workspaceItem.name"
                :value="workspaceItem.name"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="数据源类型 :">
            <el-select
              v-model="datastoreQueryFormData.storeType"
              filterable
              placeholder="请选择数据源类型"
            >
              <el-option
                v-for="storeTypeItem in storeTypeArray"
                :key="storeTypeItem.value"
                :label="storeTypeItem.label"
                :value="storeTypeItem.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="名称 :">
            <el-input v-model="datastoreQueryFormData.name" placeholder="请输入..." />
          </el-form-item>
          <el-form-item style="margin-left: auto">
            <el-button @click="reset">重置</el-button>
            <el-button @click="startQuery">查询</el-button>
            <el-button type="primary" size="small" @click="addDatastore">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>
    <div class="card-body-conterner">
      <el-table
        :data="paginatedTableData"
        style="width: 100%"
        class="datastore-table"
        header-cell-class-name="datastore-table-header-cell"
      >
        <el-table-column label="名称">
          <template #default="scope">
            <el-popover effect="light" trigger="hover" placement="top" width="auto">
              <template #default>
                <div>名称: {{ scope.row.name }}</div>
              </template>
              <template #reference>
                <el-tag>{{ scope.row.name }}</el-tag>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="工作空间" width="180">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.workspace?.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="数据源类型">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{ scope.row.type }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <span style="margin-left: 10px">{{
                scope.row.dateCreated ? dateFormat(scope.row.dateCreated) : ''
              }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="是否启用">
          <template #default="scope">
            <div style="display: flex; align-items: center">
              <el-icon><Check /></el-icon>
              <span style="margin-left: 10px">{{ scope.row.enabled }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-tooltip class="box-item" effect="dark" content="编辑" placement="bottom">
              <img
                style="margin-right: 12px; cursor: pointer"
                src="@/assets/images/edit.png"
                fit="contain"
                @click="handleEdit(scope.row)"
              />
            </el-tooltip>
            <el-tooltip class="box-item" effect="dark" content="删除" placement="bottom">
              <img
                style="cursor: pointer"
                src="@/assets/images/delete.png"
                fit="contain"
                @click="handleDelete(scope.row)"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="totalOrignTableData > 10"
        v-model:current-page="datastoreQueryFormData.pageNum"
        v-model:page-size="datastoreQueryFormData.pageSize"
        class="datastore-pagination"
        :page-sizes="[10, 20, 50, 100]"
        :background="true"
        layout="prev, pager, next, total, sizes"
        :total="totalOrignTableData"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <addOrUpdate ref="addOrUpdateRef" @update-datastore="startQuery"></addOrUpdate>
  </el-card>
</template>

<script setup lang="ts" name="authButton">
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import useWorkspaceModal from '@/composables/useWorkspace'

import filterDefaultImage from '@/assets/images/filter-default.png'
import filterSelectedImage from '@/assets/images/filter-select.png'
import { dateFormat } from '@/utils/util'
import addOrUpdate from './components/addOrUpdate.vue'
import { computed, onBeforeMount, onMounted, reactive, ref } from 'vue'
import type { IDatastore, IWorkspace } from 'geoserver-helper/interface'
import { restHelperInstance } from '@/composables/useGeoHelper'

const workspaceModal = useWorkspaceModal()
const workspaceList = workspaceModal.workspaceList

//TODO 栅格类型 后期需要和IDatastore 同步
const coverageTypes = ["GeoTIFF", "ImageMosaic", "MBTiles", "ArcGrid", "WorldImage"]

interface datastoreFormDialogExpose {
  openDialog: (opentionTypeParam?: string) => void
  setOrignDatastore: (orignDatastoreParam: IDatastore.DatastoreInfo | IDatastore.CoveragestoreInfo) => void
}
const addOrUpdateRef = ref<datastoreFormDialogExpose | undefined>()
const defaultDatastoreQueryFormData = {
  workspace: '',
  storeType: '',
  name: '',
  pageNum: 1,
  pageSize: 10,
}
const datastoreQueryFormData = reactive(JSON.parse(JSON.stringify(defaultDatastoreQueryFormData)))
const storeTypeArray = [
  {
    label: '矢量',
    value: 'datastores',
  },
  {
    label: '栅格',
    value: 'coveragestores',
  },
]
const handleEdit = (row: IDatastore.ResDatastoreInfo | IDatastore.ResCoveragestoreInfo) => {
  editDatastore(row)
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
}

const orignTableData = ref<(IDatastore.DatastoreInfo | IDatastore.CoveragestoreInfo)[]>([])
//分页数据
const paginatedTableData = computed(() => {
    return orignTableData.value.slice((datastoreQueryFormData.pageNum - 1) * datastoreQueryFormData.pageSize, datastoreQueryFormData.pageNum * datastoreQueryFormData.pageSize)
})
// 数据总数
const totalOrignTableData = ref(0)
const startQuery = () => {
  if (datastoreQueryFormData.workspace) {
    totalOrignTableData.value = 0
    orignTableData.value = []
    let promiseArray: Promise<
      boolean | IDatastore.ResDatastoreList | IDatastore.ResCoveragestoreList
    >[] = []
    if (datastoreQueryFormData.storeType) {
      if (datastoreQueryFormData.storeType == 'datastores') {
        promiseArray = [
          restHelperInstance.getDatastoreListApi(datastoreQueryFormData.workspace),
        ].map((item) => item.catch(() => Promise.resolve(true)))
      } else if (datastoreQueryFormData.storeType == 'coveragestores') {
        promiseArray = [
          restHelperInstance.getCoveragestoresListApi(datastoreQueryFormData.workspace),
        ].map((item) => item.catch(() => Promise.resolve(true)))
      }
    } else {
      promiseArray = [
        restHelperInstance.getDatastoreListApi(datastoreQueryFormData.workspace),
        restHelperInstance.getCoveragestoresListApi(datastoreQueryFormData.workspace),
      ].map((item) => item.catch(() => Promise.resolve(true)))
    }
    Promise.all(promiseArray).then((res) => {
      res.forEach((singleDatastoreList) => {
        if (typeof singleDatastoreList !== 'boolean') {
          if (
            (singleDatastoreList as IDatastore.ResDatastoreList).dataStores &&
            (singleDatastoreList as IDatastore.ResDatastoreList).dataStores.dataStore
          ) {
            const currentDatastore = singleDatastoreList as IDatastore.ResDatastoreList
            if (currentDatastore.dataStores.dataStore instanceof Array) {
              currentDatastore.dataStores.dataStore.forEach(singleDatastore => {
                if (datastoreQueryFormData.name) {
                  if (singleDatastore.name.includes(datastoreQueryFormData.name)) {
                    totalOrignTableData.value += 1
                    restHelperInstance
                      .getDatastoreInfoApi(
                        datastoreQueryFormData.workspace,
                        singleDatastore.name,
                      )
                      .then((storeRes) => {
                        orignTableData.value.push(storeRes.dataStore)
                      })
                  }
                } else {
                  totalOrignTableData.value += 1
                  restHelperInstance
                    .getDatastoreInfoApi(
                      datastoreQueryFormData.workspace,
                      singleDatastore.name,
                    )
                    .then((storeRes) => {
                      orignTableData.value.push(storeRes.dataStore)
                    })
                }
              })
            }
          } else if (
            (singleDatastoreList as IDatastore.ResCoveragestoreList).coverageStores &&
            (singleDatastoreList as IDatastore.ResCoveragestoreList).coverageStores.coverageStore
          ) {
            const currentDatastore = singleDatastoreList as IDatastore.ResCoveragestoreList
            if (currentDatastore.coverageStores.coverageStore instanceof Array) {
              currentDatastore.coverageStores.coverageStore.forEach((singleDatastore) => {
                if (datastoreQueryFormData.name) {
                  if (singleDatastore.name.includes(datastoreQueryFormData.name)) {
                    totalOrignTableData.value += 1
                    restHelperInstance
                      .getCoveragestoreInfoApi(
                        datastoreQueryFormData.workspace,
                        singleDatastore.name,
                      )
                      .then((storeRes) => {
                        orignTableData.value.push(storeRes.coverageStore)
                      })
                  }
                } else {
                  totalOrignTableData.value += 1
                  restHelperInstance
                    .getCoveragestoreInfoApi(
                      datastoreQueryFormData.workspace,
                      singleDatastore.name,
                    )
                    .then((storeRes) => {
                      orignTableData.value.push(storeRes.coverageStore)
                    })
                }
              })
            }
          }
        }
      })
    })
  } else {
    ElMessage({
      type: 'warning',
      message: '请先选择工作空间',
    })
  }
}

/**
 * @description: 重置
 * @return {*}
 */
const reset = () => {
  datastoreQueryFormData.value = {
    ...JSON.parse(JSON.stringify(defaultDatastoreQueryFormData)),
    workspaceId: workspaceModal.defaultWorkspace.value?.name,
  }
}

const addDatastore = () => {
  if (addOrUpdateRef.value) {
    addOrUpdateRef.value.openDialog('新增')
  }
}
const editDatastore = (
  readyToUpdateDatastore: IDatastore.ResDatastoreInfo | IDatastore.ResCoveragestoreInfo,
) => {
  if (addOrUpdateRef.value) {
    addOrUpdateRef.value.setOrignDatastore(
      (readyToUpdateDatastore as IDatastore.ResDatastoreInfo).dataStore ||
        (readyToUpdateDatastore as IDatastore.ResCoveragestoreInfo).coverageStore,
    )
    addOrUpdateRef.value.openDialog('编辑')
  }
}
/**
 * @description: 删除数据源
 * @param {*} row
 * @return {*}
 */
const handleDelete = (row: IDatastore.DatastoreInfo | IDatastore.CoveragestoreInfo) => {
  let workspaceName = row.workspace.name
  let storeName = row.name
  ElMessageBox.confirm(`确认删除${storeName}么?`, '', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      if(coverageTypes.includes(row.type)){
        restHelperInstance.deleteCoverageDatastoreApi(workspaceName, storeName, true).then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          startQuery()
        })
      }else {
        restHelperInstance.deleteDatastoreApi(workspaceName, storeName, true).then(() => {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
          startQuery()
        })
      }
    })
    .catch(() => {})
}
onBeforeMount(() => {
  // 此处执行一次后确保 workspaceList 有值
  workspaceModal.getWorkspaceList()
})
onMounted(() => {
  workspaceModal.getDefaultWorkspace().then(()=>{
    datastoreQueryFormData.workspace = workspaceModal.defaultWorkspace.value.name
    startQuery()
  })
})
</script>

<style scoped lang="scss">
@import './index';
</style>
